/* 
 * Modbus app for RTU.
 * Copyright (c) 2012  apleilx
 * All rights reserved.
 * no limite
 */

/* ----------------------- Platform includes --------------------------------*/
#define _MAPP_MODULE_
#include "mbapp.h"
#include "os_obj.h"                                          // RTOS object definitions
#include "sys_task.h"
#include "common.h"

#define TEST_MODE       MB_RTU_SLAVE

mb_baud_tab_create;
    
uint8_t mbTestErrCnt = 0;
uint8_t mbTestOkCnt = 0;

typedef struct
{
    uint16_t reg_r[64];
    uint16_t reg_w[64];
    uint16_t pv_r[64];
    uint16_t pv_w[64];
    uint16_t obj_size;
} mb_tst_type;

mb_tst_type mb_tst;

void rcv_end_handle_comp(uint8_t ErrSt);

/******************************************************************************
* @brief   	Slave device handle.
*               
* @param   none
*
* @return  none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/   
void modbus_task (ULONG thread_input)
{
    UINT os_err;
    ULONG event;
    mb_cmd_buff_type mcmd;
		
    mb_obj_init(&mb.obj08);

    //slave config
    mb08_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_115200], MB_PAR_NONE);
    mb.obj08.slave_id = 1;
    mb.obj08.os_event_send = mb_os_send;
    mb.obj08.os_event_base = 1<<4;
	mb.obj08.rtu_length_cut = 1;
    
    mb_obj_init(&mb.obj06);

    //master config
    mb06_Init(MB_RTU_MASTER, mb_baud_tab[MB_BAUD_115200], MB_PAR_NONE);
    mb.obj06.slave_id = 1;
    mb.obj06.rtu_master_delay_set = 3;
    mb.obj06.rcv_end_handle_comp = rcv_end_handle_comp;
    mb.obj06.os_event_send = mb_os_send;
    mb.obj06.os_event_base = 2<<4;
	mb.obj06.rtu_length_cut = 1; 
   
    //cmd config
	mcmd.device_id = 0;
	mcmd.cmd = FUN_CODE_READ_COILS;
	mcmd.dat = mb_tst.pv_w;
	mcmd.dat_addr = 0;
	mcmd.amount = 48;
	mcmd.call_back=0;
    mb.obj06.api->stc_cmd_req(0, &mcmd);
	
	mcmd.cmd = FUN_CODE_READ_DISCRETE;
	mb.obj06.api->stc_cmd_req(1, &mcmd);
	
	mcmd.cmd = FUN_CODE_W_R_MULTIPLE_REG;
	mb.obj06.api->stc_cmd_req(2, &mcmd);
	
	mcmd.cmd = FUN_CODE_W_R_MULTIPLE_REG;
	mb.obj06.api->stc_cmd_req(3, &mcmd);
    
	mcmd.cmd = FUN_CODE_WRITE_MULTIPLE_REG;
	mb.obj06.api->stc_cmd_req(4, &mcmd);
	
	mcmd.cmd = FUN_CODE_WRITE_MULTIPLE_COIL;
	mb_tst.pv_w[0] = 0;
	mb.obj06.api->stc_cmd_req(5, &mcmd);
	
    //task handle
    for(;;)
    {
        // wait modbus event
        os_err = tx_event_flags_get(os_obj.eid_mb, 
                           0xFFFF,
                           TX_OR_CLEAR, 
                           &event,
                           ms_ticks(3000));
        // os_api_exe_check();
        
        (void)os_err;

        mb_poll(&mb.obj08);
        
        mb_poll(&mb.obj06);
        
        mb_tst.obj_size = sizeof(mb.obj06);
    }
}

void rcv_end_handle_comp(uint8_t ErrSt)
{

}

